package com.sunsharing.common.register.simplexml;

import com.sunsharing.common.anno.Factory;
import com.sunsharing.common.config.*;
import com.sunsharing.common.utils.IOUtils;
import com.sunsharing.common.utils.StringUtils;
import com.sunsharing.common.register.Register;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-14
 * Time: 上午10:31
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="XML")
public class XmlRegister implements Register {

    Logger logger = Logger.getLogger(XmlRegister.class);

    RegisterModel registerModel = null;

    static Lock lock =  new ReentrantLock();

    @Override
    public void load()
    {
        lock.lock();
        try
        {
            if(registerModel!=null)
            {
                logger.info("已经初始化推出");
                return;
            }else
            {
                registerModel = new RegisterModel();
            }
            String path = StringUtils.getClassPath();
            File temp = new File(path+"register.xml");
            String xml = IOUtils.readContent(temp);
            Document doc = DocumentHelper.parseText(xml);

            Element root = doc.getRootElement();
            //处理Node
            List<Element> nodes = root.element("Nodes").elements("Node");
            for(Element ele:nodes)
            {
                NodeModel nodeModel = new NodeModel();
                nodeModel.ip = ele.attributeValue("ip");
                nodeModel.nodeId = ele.attributeValue("nodeId");
                nodeModel.domain = ele.attributeValue("domain")==null?"default":ele.attributeValue("domain");
                nodeModel.rootpath = ele.attributeValue("filerootpath");

                List<Element> chs = ele.elements("channel");
                for(Element ch:chs)
                {
                    ChannelModel m = new ChannelModel();
                    m.name = ch.attributeValue("name");
                    m.type = ch.attributeValue("type");
                    m.port = ch.attributeValue("port");
                    m.mailboxType = ch.attributeValue("mailboxType");
                    m.lisen = ch.attributeValue("lisen");
                    m.nodeModel = nodeModel;
                    nodeModel.channelModels.add(m);
                }
                registerModel.nodes.add(nodeModel);
            }

            //处理Router
            List<Element> routes = root.element("Routers").elements("Route");
            for(Element rout:routes)
            {
                RouterModel routerModel = new RouterModel();
                routerModel.fromNode = registerModel.searchNodeById(rout.attributeValue("fromNode"));
                routerModel.toNode = registerModel.searchNodeById(rout.attributeValue("toNode"));

                if(!StringUtils.isBlank(rout.attributeValue("byClient")))
                {
                    routerModel.byClient = new Boolean(rout.attributeValue("byClient"));
                }
                if(!StringUtils.isBlank(rout.attributeValue("fromPro")))
                {
                    routerModel.fromPro = rout.attributeValue("fromPro");
                }
                if(!StringUtils.isBlank(rout.attributeValue("toPro")))
                {
                    routerModel.toPro = rout.attributeValue("toPro");
                }
                if(!StringUtils.isBlank(rout.attributeValue("twoWay")))
                {
                    routerModel.isTwoWay = new Boolean(rout.attributeValue("twoWay"));
                }
                registerModel.routers.add(routerModel);
            }
            //处理Service
            List<Element> services = root.element("Services").elements("Service");
            for(Element ele:services)
            {
                ServiceModel service = new ServiceModel();
                service.name = ele.attributeValue("name");
                service.operator = ele.attributeValue("operator");
                service.limit = ele.attributeValue("limit");

                List<Element> wsdls = ele.elements("wsdl");
                for(Element ws:wsdls)
                {
                    WsdlModel w = new WsdlModel();
                    w.nodeId = ws.attributeValue("nodeId");
                    w.wsdl = ws.attributeValue("wsdl");
                    service.wsdlList.add(w);
                }
                registerModel.services.add(service);
            }

            List<Element> flows = root.element("Services").elements("Flow");
            for(Element ele:flows)
            {
                FlowModel service = new FlowModel();
                service.name = ele.attributeValue("name");
                registerModel.services.add(service);
            }
        }catch (Exception e)
        {
             throw new RuntimeException("加载注册信息失败");
        }finally{
           lock.unlock();
        }
    }

    public List<NodeModel> getNodes()
    {
         if(registerModel==null)
         {
             load();
         }
        return registerModel.nodes;
    }

    public List<RouterModel> getRouters()
    {
        if(registerModel==null)
        {
            load();
        }
        return registerModel.routers;
    }

    @Override
    public RegisterModel getRegisterModel() {
        return this.registerModel;
    }

    @Override
    public void addNode() {

    }

    @Override
    public void removeNode() {
    }

    @Override
    public void refresh() {
        registerModel = null;
        load();
    }

    public List<ServiceModel> getServiceModel()
    {
        return this.registerModel.services;
    }

}
